import {getToken, setToken, removeToken, setUserData} from '../../utils/auth'
import {GTuser} from '../../api/user.js'
import {GTuserInfo} from '../../api/userInfo'
import md5 from 'js-md5'
import router from '@/router'
const user = {
  state: {
    userName: '',
    userId: '',
    avatorImgPath: '',
    token: getToken(),
    access: '',
    hasGetInfo: false,
    roles: [],
    setting: {
      articlePlatform: []
    }
  },
  mutations: {
    setAvator (state, avatorPath) {
      state.avatorImgPath = avatorPath
    },
    setUserId (state, id) {
      state.userId = id
    },
    setUserName (state, name) {
      state.userName = name
    },
    setAccess (state, access) {
      state.access = access
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    LOGIN_SUCCESS: () => {
      console.log('login success')
    },
    LOGOUT_USER: state => {
      state.user = ''
    }
  },

  actions: {
    // 登录
    handleLogin ({ commit }, {userName, password,code}) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        GTuser({
          userName,
          password,
          code
        }).then(res => {
          const data = res
          if(data){
            commit('setToken', data.token)
            resolve()
          }
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setToken', '')
          commit('setAccess', [])
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          GTuserInfo(getToken()).then(res => {
            const data = res[0]
            commit('setAvator', data.avator)
            commit('setUserName', data.name)
            commit('setUserId', data.userId)
            commit('setAccess', data.access)
            commit('setHasGetInfo', true)
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
    // 邮箱登录
    LoginByEmail ({commit}, userInfo) {
      return new Promise((resolve) => {

      })
    },
    // 获取用户信息
    GetInfo ({commit, state}, userInfo) {
      return new Promise((resolve) => {
        state.token = userInfo.token
        setToken(userInfo.token)
        var str = JSON.stringify(userInfo)
        setUserData(str)
        commit('SET_EMAIL', userInfo.email)
        resolve()
      })
    },
    // 第三方验证登录
    LoginByThirdparty({commit, state}, code) {
      return new Promise((resolve, reject) => {
        commit('SET_CODE', code);
      });
    },
    // 登出
    LogOut ({commit, state}) {
      return new Promise((resolve) => {
        commit('setToken', '')
        commit('setAccess', [])
        removeToken()
        resolve()
        // logout 直接写一个登出接口 暂时只做前端登出
        // logout('', () => {
        //   commit('SET_TOKEN', '')
        //   commit('SET_EMAIL', '')
        //   removeToken()
        //   resolve()
        // })
      })
    },

    // 前端 登出
    FedLogOut ({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },
    // 动态修改权限
    ChangeRole({commit}, role) {
      return new Promise(resolve => {
        commit('SET_ROLES', [role]);
        commit('SET_TOKEN', role);
        setToken(role);
        resolve();
      })
    }
  }
};

export default user;
